<template>
    <div class="layout-root">
        <aside class="sidebar-fixed" :class="{ collapsed: isCollapse }">
            <Sidebar :isCollapse="isCollapse" />
        </aside>
        <div class="main-area" :style="{ marginLeft: isCollapse ? '64px' : '160px' }">
            <el-header class="main-header">
                <MainNavbar :isCollapse="isCollapse" @update:isCollapse="val => isCollapse = val" />
            </el-header>
            <div class="tabs-sticky">
                <TabsView />
            </div>
            <el-main class="main-content">
                <transition name="fade-slide" mode="out-in">
                    <router-view :key="$route.fullPath" />
                </transition>
            </el-main>
        </div>

        <!-- 全局修改密码对话框 -->
        <el-dialog v-model="changePwdDialogVisible" title="修改密码" width="450px" :close-on-click-modal="false">
            <el-form :model="pwdForm" :rules="pwdRules" ref="pwdFormRef" label-width="80px" class="change-pwd-form">
                <el-form-item label="原密码" prop="oldPwd">
                    <el-input v-model="pwdForm.oldPwd" type="password" placeholder="请输入原密码" show-password clearable />
                </el-form-item>
                <el-form-item label="新密码" prop="newPwd">
                    <el-input v-model="pwdForm.newPwd" type="password" placeholder="请输入新密码" show-password clearable />
                    <div class="password-tips" v-if="pwdForm.newPwd">
                        <div class="tip-item" :class="{ 'valid': pwdForm.newPwd.length >= 6 }">
                            <el-icon><Check v-if="pwdForm.newPwd.length >= 6" /><Close v-else /></el-icon>
                            <span>密码长度至少6位</span>
                        </div>
                        <div class="tip-item" :class="{ 'valid': pwdForm.newPwd !== pwdForm.oldPwd }">
                            <el-icon><Check v-if="pwdForm.newPwd !== pwdForm.oldPwd" /><Close v-else /></el-icon>
                            <span>新密码不能与原密码相同</span>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPwd">
                    <el-input v-model="pwdForm.confirmPwd" type="password" placeholder="请再次输入新密码" show-password clearable />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="changePwdDialogVisible = false" size="large">取消</el-button>
                    <el-button type="primary" @click="handleChangePwd" size="large" :loading="changePwdLoading">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import Sidebar from '../components/common/Sidebar.vue'
import MainNavbar from '../components/common/MainNavbar.vue'
import TabsView from '../components/common/TabsView.vue'
import { ElMessage } from 'element-plus'
import { changePassword } from '@/api/user'
import { Check, Close } from '@element-plus/icons-vue'
import { baseURL } from '@/utils/request'

const isCollapse = ref(false)

// 修改密码相关变量
const changePwdDialogVisible = ref(false)
const changePwdLoading = ref(false)
const pwdFormRef = ref()
const pwdForm = ref({ oldPwd: '', newPwd: '', confirmPwd: '' })

// 修改密码表单验证规则
const pwdRules = {
  oldPwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 1, message: '原密码不能为空', trigger: 'blur' }
  ],
  newPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
    { max: 50, message: '密码长度不能超过50位', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && value === pwdForm.value.oldPwd) {
          callback(new Error('新密码不能与原密码相同'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPwd: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdForm.value.newPwd) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

/**
 * 打开修改密码对话框
 */
function openChangePasswordDialog() {
  changePwdDialogVisible.value = true
  resetPwdForm()
}

/**
 * 重置修改密码表单
 */
function resetPwdForm() {
  if (pwdFormRef.value) {
    pwdFormRef.value.resetFields()
  }
  pwdForm.value = { oldPwd: '', newPwd: '', confirmPwd: '' }
}

/**
 * 处理修改密码
 */
async function handleChangePwd() {
  if (!pwdFormRef.value) return
  await pwdFormRef.value.validate(async (valid) => {
    if (valid) {
      changePwdLoading.value = true
      try {
        // 移除网络连接测试，直接进行密码修改
        // 从本地存储获取用户信息
        const tokenData = localStorage.getItem('token')
        if (!tokenData) {
          ElMessage.error('用户未登录')
          return
        }
        
        let userId = null
        try {
          const parsedTokenData = JSON.parse(tokenData)
          const userInfo = parsedTokenData.userInfo || parsedTokenData.data?.userInfo || parsedTokenData
          userId = userInfo?.userId
        } catch (error) {
          console.error('解析用户信息失败:', error)
          ElMessage.error('用户信息解析失败')
          return
        }
        
        if (!userId) {
          ElMessage.error('用户信息不完整')
          return
        }
        console.log('请求数据:', {
          oldPassword: pwdForm.value.oldPwd,
          newPassword: pwdForm.value.newPwd
        })

        const response = await changePassword(userId, {
          oldPassword: pwdForm.value.oldPwd,
          newPassword: pwdForm.value.newPwd
        })

        if (response && response.code === 200) {
          ElMessage.success('密码修改成功！')
          changePwdDialogVisible.value = false
          resetPwdForm()
        } else {
          const errorMessage = response?.message || response?.data?.message || '密码修改失败'
          ElMessage.error(errorMessage)
        }
      } catch (error) {
        console.error('修改密码失败:', error)
        console.error('错误详情:', {
          message: error.message,
          response: error.response,
          request: error.request,
          config: error.config
        })
        
        let errorMessage = '密码修改失败'
        
        if (error.response) {
          console.error('服务器响应错误:', error.response.data)
          const responseData = error.response.data
          if (responseData?.message) {
            errorMessage = responseData.message
          } else if (responseData?.data?.message) {
            errorMessage = responseData.data.message
          } else if (typeof responseData === 'string') {
            errorMessage = responseData
          }
        } else if (error.request) {
          console.error('网络请求错误:', error.request)
          errorMessage = '网络连接失败，请检查网络后重试'
        } else {
          console.error('其他错误:', error.message)
          errorMessage = error.message || '未知错误'
        }
        
        ElMessage.error(errorMessage)
      } finally {
        changePwdLoading.value = false
      }
    }
  })
}

onMounted(() => {
  // 监听修改密码事件
  window.addEventListener('open-change-password', openChangePasswordDialog)
})

onUnmounted(() => {
  // 清理事件监听器
  window.removeEventListener('open-change-password', openChangePasswordDialog)
})
</script>

<style scoped>
body,
html,
#app,
.layout-root {
    height: 100vh;
    width: 100vw;
    margin: 0;
    padding: 0;
    overflow-x: hidden;
    box-sizing: border-box;
    position: fixed;
    top: 0;
    left: 0;
}

.main-area {
    height: 100vh;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    transition: margin-left 0.2s;
    background: #f5f6fa;
    overflow-y: auto;
    overflow-x: hidden;
}

.main-header {
    background: #fff;
    border-bottom: 1px solid #f0f0f0;
    padding: 0;
    height: 64px;
    position: relative;
    z-index: 10;
    flex-shrink: 0;
}

.tabs-sticky {
  position: relative;
  z-index: 9;
  background: #fff;
  flex-shrink: 0;
}

.main-content {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 0;
    background: #f5f6fa;
}

.sidebar-fixed {
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh;
    width: 160px;
    background: #fff;
    border-right: 1px solid #f0f0f0;
    transition: width 0.2s;
    z-index: 100;
    overflow: hidden;
}

.sidebar-fixed.collapsed {
    width: 64px;
}

.main-content>* {
    max-width: 100%;
    box-sizing: border-box;
    overflow-x: auto;
}

.layout-root {
    min-height: 100vh;
}

/* 过渡动画样式 */
.fade-slide-enter-active,
.fade-slide-leave-active {
    transition: opacity 0.3s, transform 0.3s;
}

.fade-slide-enter-from {
    opacity: 0;
    transform: translateX(20px);
}

.fade-slide-leave-to {
    opacity: 0;
    transform: translateX(-20px);
}

/* 对话框底部按钮区域样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

/* 修改密码对话框样式 */
.change-pwd-form {
  padding: 20px 0;
}

/* 修改密码对话框标题样式 */
:deep(.el-dialog__title) {
  font-weight: 600 !important;
  font-size: 18px !important;
  letter-spacing: 0.5px !important;
}

/* 修改密码对话框标题底部边框 */
:deep(.el-dialog__header) {
  border-bottom: 1px solid #e4e7ed !important;
  padding-bottom: 15px !important;
  margin-bottom: 20px !important;
}

.change-pwd-form .el-form-item {
  margin-bottom: 20px;
}

.change-pwd-form .el-input {
  width: 100%;
}

.change-pwd-form .el-form-item__label {
  font-weight: 500;
  color: var(--text-color);
}

.change-pwd-form :deep(.el-input__wrapper) {
  border: none !important;
  border-bottom: 1px solid #dcdfe6 !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  background: transparent !important;
}

.change-pwd-form :deep(.el-input__wrapper:hover) {
  border-bottom-color: #409eff !important;
}

.change-pwd-form :deep(.el-input__wrapper.is-focus) {
  border-bottom-color: #409eff !important;
  border-bottom-width: 1px !important;
}

.change-pwd-form :deep(.el-input__inner) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

/* 密码提示样式 */
.password-tips {
  margin-top: 8px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #6c757d;
  margin-bottom: 4px;
}

.tip-item:last-child {
  margin-bottom: 0;
}

.tip-item.valid {
  color: #28a745;
}

.tip-item .el-icon {
  font-size: 12px;
}

.tip-item.valid .el-icon {
  color: #28a745;
}

.tip-item:not(.valid) .el-icon {
  color: #dc3545;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .sidebar-fixed {
        display: none; /* 在移动端完全隐藏侧边栏 */
    }
    
    .main-area {
        margin-left: 0 !important; /* 移除左边距 */
    }
    
    .main-header {
        height: 60px; /* 调整导航栏高度 */
    }
    
    .main-content {
        padding-top: 0; /* 移除顶部内边距 */
    }
}

@media (max-width: 480px) {
    .sidebar-fixed {
        display: none;
    }
    
    .main-area {
        margin-left: 0 !important;
    }
    
    .main-header {
        height: 50px; /* 更小的导航栏高度 */
    }
}
</style>
